<template>
    <div class="conversation-container">
      <!-- 待接入会话列表 -->
      <div class="conversation-list">
        <div class="conversation-list-item">
          <div class="conversation-list-title">待接入 {{ pendingConversations.length }}</div>
          <div class="conversation-list-body">
            <!-- 遍历待接入会话列表 -->
            <div
              v-for="(conversation, key) in pendingConversations" 
              :key="key"
              @click="router.push(chat(conversation))"
            >
              <div class="conversation-item">
                <div class="conversation-item-head">
                  <!-- 显示会话头像 -->
                  <img :src="conversation.data.avatar" class="conversation-item-avatar"/>
                </div>
                <div class="item-info">
                  <!-- 显示会话名称 -->
                  <div class="item-info-name">{{ conversation.data.name }}</div>
                  <!-- 根据消息类型显示不同内容 -->
                  <div v-if="conversation.lastMessage.type === 'text'" class="item-info-message">
                    {{ conversation.lastMessage.payload.text }}
                  </div>
                  <div v-else-if="conversation.lastMessage.type === 'image'" class="item-info-message">[图片消息]</div>
                  <div v-else-if="conversation.lastMessage.type === 'video'" class="item-info-message">[视频消息]</div>
                  <div v-else-if="conversation.lastMessage.type === 'audio'" class="item-info-message">[语音消息]</div>
                  <div v-else-if="conversation.lastMessage.type === 'order'" class="item-info-message">[自定义消息:订单]
                  </div>
                  <div v-else-if="conversation.lastMessage.type === 'CS_END'" class="item-info-message">会话已结束</div>
                  <div v-else-if="conversation.lastMessage.type === 'CS_ACCEPT'" class="item-info-message">接入成功</div>
                  <div v-else-if="conversation.lastMessage.type === 'CS_TRANSFER'" class="item-info-message">
                    {{
                      conversation.lastMessage.senderId === currentAgent.id ? `已转接给` +
                        conversation.lastMessage.payload.transferTo.data.name : '已接入来自' +
                        conversation.lastMessage.senderData.name + '的转接'
                    }}
                  </div>
                  <div v-else class="item-info-message">[未识别内容]</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 已接入会话列表 -->
        <div class="conversation-list-item">
          <div class="conversation-list-title">已接入 {{ conversations.length }}</div>
          <div v-if="conversations.length" class="conversation-list-body">
            <!-- 遍历已接入会话列表 -->
            <!-- <div
              v-for="(conversation, key) in conversations" 
              :key="key"
              @click="router.push(chat(conversation))"
              @contextmenu.prevent.stop="e => showRightClickMenu(e,conversation)"
            > -->
            <router-link
            tag="div" :to="chat(conversation)" replace
            v-for="(conversation, key) in conversations" :key="key"
          >
              <div class="conversation-item" :class="{ 'router-link-active': isActive(conversation) }">
                <div class="conversation-item-head">
                  <img :src="conversation.data.avatar" class="conversation-item-avatar"/>
                  <span v-if="conversation.unread" class="conversation-item-unread">{{ conversation.unread }}</span>
                </div>
                <div class="conversation-item-info">
                  <div class="item-info-top">
                    <div class="item-info-name">{{ conversation.data.name }}</div>
                    <div class="item-info-time">{{ formatDate(conversation.lastMessage.timestamp) }}</div>
                  </div>
                  <div class="item-info-bottom">
                    <div v-if="conversation.lastMessage.status === 'sending'" class="item-info-sending"></div>
                    <div v-if="conversation.lastMessage.status === 'fail'" class="item-info-failed"></div>
                    <div v-if="conversation.lastMessage.type === 'text'" class="item-info-message">
                      {{ conversation.lastMessage.senderId === currentAgent.id ? '你' : conversation.lastMessage.senderData.name }}:
                      {{ conversation.lastMessage.payload.text }}
                    </div>
                    <div v-else-if="conversation.lastMessage.type === 'image'" class="item-info-message">[图片消息]</div>
                    <div v-else-if="conversation.lastMessage.type === 'video'" class="item-info-message">[视频消息]</div>
                    <div v-else-if="conversation.lastMessage.type === 'audio'" class="item-info-message">[语音消息]</div>
                    <div v-else-if="conversation.lastMessage.type === 'order'" class="item-info-message">[自定义消息:订单]
                    </div>
                    <div v-else-if="conversation.lastMessage.type === 'CS_END'" class="item-info-message">会话已结束</div>
                    <div v-else-if="conversation.lastMessage.type === 'CS_ACCEPT'" class="item-info-message">接入成功</div>
                    <div v-else-if="conversation.lastMessage.type === 'CS_TRANSFER'" class="item-info-message">
                      {{
                        conversation.lastMessage.senderId === currentAgent.id ? `已转接给` +
                          conversation.lastMessage.payload.transferTo.data.name : '已接入来自' +
                          conversation.lastMessage.senderData.name + '的转接'
                      }}
                    </div>
                    <div v-else class="item-info-message">[未识别内容]</div>
                  </div>
                </div>
              </div>
            </router-link>
          </div>
        </div>
        <div 
          v-if="rightClickMenu.visible" 
          :style="{'left': rightClickMenu.x + 'px', 'top': rightClickMenu.y + 'px'}"
          class="action-box"
          v-click-outside="hideRightClickMenu"
        >
          <div class="action-item" @click="topConversation">{{ rightClickMenu.conversation.top ? '取消置顶' : '置顶' }}</div>
          <div class="action-item" @click="deleteConversation">删除聊天</div>
        </div>
      </div>
      <div class="conversation-main">
        <router-view :key="route.params.id"></router-view>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onBeforeUnmount } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { formatDate } from '../../utils/utils';
  import  {useCounterStore} from '../../store/index';
  import GoEasy from 'goeasy';
  
  const router = useRouter();
  const route = useRoute();
  
  const pendingConversations = ref([]);
  const conversations = ref([]);
  const currentAgent = ref(null);
  const rightClickMenu = ref({
    conversation: null,
    visible: false,
    x: null,
    y: null,
  });
// 在GoEasy配置中添加
const goEasy = GoEasy.getInstance({
  host: 'hangzhou.goeasy.io',	//应用所在的区域地址: 【hangzhou.goeasy.io |singapore.goeasy.io】
  appkey: 'BC-3b18447e8c3d45b0901e3fb6444dda37', // common key,
  modules: ['im']
});
  // Check if conversation is active
  const isActive = (conversation) => {
    return route.params.id === conversation.id;
  };
  
  const chat = (conversation) => {
    goEasy.disconnect({
        onSuccess: function(){
            console.log("GoEasy disconnect successfully.")
        },
        onFailed: function(error){
            console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
        }
    });
    return {
      path: '/conversations/chat/' + conversation.id,
      query: {
        name: conversation.data.name,
        avatar: conversation.data.avatar
      }
    };
  };
  
  const showRightClickMenu = (e, conversation) => {
    rightClickMenu.value.conversation = conversation;
    rightClickMenu.value.visible = true;
    rightClickMenu.value.x = e.pageX;
    rightClickMenu.value.y = e.pageY;
  };
  
  const hideRightClickMenu = () => {
    rightClickMenu.value.visible = false;
  };
  
  const topConversation = () => {
    const conversation = rightClickMenu.value.conversation;
    const description = conversation.top ? '取消置顶' : '置顶';
    goEasy.im.topConversation({
      top: !conversation.top,
      conversation: conversation,
      onSuccess: function() {
        console.log(description, '成功');
      },
      onFailed: function(error) {
        console.log(description, '失败：', error);
      },
    });
  };
  
  const deleteConversation = () => {
    if (!rightClickMenu.value.conversation.ended) {
      alert("删除失败：会话尚未结束");
      return;
    }
    if (confirm('确认要删除这条会话吗？')) {
      goEasy.im.removeConversation({
        conversation: rightClickMenu.value.conversation,
        onSuccess: function() {
          console.log('删除会话成功');
        },
        onFailed: function(error) {
          console.log(error);
        },
      });
    }
  };
  
  const loadConversations = () => {
    goEasy.im.pendingConversations({
      onSuccess: (result) => {
        pendingConversations.value = result.content.conversations;
      },
      onFailed: (error) => {
        console.log('获取待接入列表失败, code:' + error.code + 'content:' + error.content);
      },
    });
    
    goEasy.im.latestConversations({
      onSuccess: (result) => {
        conversations.value = result.content.conversations;
      },
      onFailed: (error) => {
        console.log('获取已接入列表失败, code:' + error.code + 'content:' + error.content);
      },
    });
  };
  
  const renderPendingConversations = (content) => {
    pendingConversations.value = content.conversations;
  };
  
  const renderLatestConversations = (content) => {
    conversations.value = content.conversations;
  };
  // 定义一个连接GoEasy的函数
  const connectGoEasy = () => {
  // 返回一个Promise对象
  return new Promise((resolve, reject) => {
    // 连接GoEasy
    goEasy.connect({
      // 传入当前代理的id
      id: currentAgent.value.id,
      // 传入当前代理的name和avatar
      data: { name: currentAgent.value.name, avatar: currentAgent.value.avatar },
      // 连接成功时调用resolve
      onSuccess: () => resolve(),
      // 连接失败时调用reject，并传入错误信息
      onFailed: (error) => reject(error)
    });
  });
};
  
 onMounted( () => {
  // 获取全局数据
  currentAgent.value = useCounterStore().currentAgent;

   
   
     connectGoEasy();
  
  // 然后加载数据
  loadConversations();
  
  // 设置监听
  goEasy.im.on(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, renderLatestConversations);
  goEasy.im.on(GoEasy.IM_EVENT.PENDING_CONVERSATIONS_UPDATED, renderPendingConversations);
});
  
  onBeforeUnmount(() => {
    goEasy.disconnect({
        onSuccess: function(){
            console.log("GoEasy disconnect successfully.")
        },
        onFailed: function(error){
            console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
        }
    });
    goEasy.im.off(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, renderLatestConversations);
    goEasy.im.off(GoEasy.IM_EVENT.PENDING_CONVERSATIONS_UPDATED, renderPendingConversations);
  });
  
  // Click outside directive
  const vClickOutside = {
    beforeMount(el, binding) {
      el.clickOutsideEvent = function(event) {
        if (!(el === event.target || el.contains(event.target))) {
          binding.value();
        }
      };
      document.addEventListener('click', el.clickOutsideEvent);
    },
    unmounted(el) {
      document.removeEventListener('click', el.clickOutsideEvent);
    },
  };
  </script>
  
  <style scoped>
  /* Your existing styles remain the same */
  .conversation-container {
    width: 100%;
    height: 100%;
    display: flex;
    background: #FFFFFF;
  }
  
  .conversation-list {
    width: 220px;
    border-right: 1px solid #eee;
    display: flex;
    flex-direction: column;
    padding: 10px;
    position: relative;
  }
  
  .conversation-list-title {
    font-size: 15px;
    margin: 5px 10px;
    color: rgba(0, 0, 0, 0.9);
  }
  
  .conversation-list-body {
    overflow-y: auto;
    max-height: 350px;
    scrollbar-width: none;
    -ms-overflow-style: none;
  }
  
  .conversation-list-body::-webkit-scrollbar {
    display: none;
  }
  
  .action-box {
    width: 100px;
    height: 60px;
    background: #ffffff;
    border: 1px solid #cccccc;
    position: fixed;
    z-index: 100;
    border-radius: 5px;
  }
  
  .action-item {
    padding-left: 15px;
    line-height: 30px;
    font-size: 13px;
    color: #262628;
    cursor: pointer;
  }
  
  .action-item:hover {
    background: #dddddd;
  }
  
  .conversation-item {
    display: flex;
    padding: 10px;
    cursor: pointer;
  }
  
  .conversation-item-head {
    position: relative;
    margin-right: 5px;
  }
  
  .conversation-item-avatar {
    width: 40px;
    height: 40px;
    border-radius: 4px;
  }
  
  .conversation-item-unread {
    position: absolute;
    top: -9px;
    right: -9px;
    width: 18px;
    height: 18px;
    line-height: 18px;
    border-radius: 50%;
    text-align: center;
    color: #fff;
    font-size: 12px;
    background-color: #fa5151;
  }
  
  .conversation-item-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  
  .item-info-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .item-info-name {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    font-size: 15px;
    width: 80px;
    line-height: 25px;
    color: #333333;
  }
  
  .item-info-time {
    color: #666666;
    font-size: 12px;
  }
  
  .item-info-bottom {
    display: flex;
    align-items: center;
  }
  
  .item-info-message {
    font-size: 12px;
    line-height: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 150px;
    color: #606266;
  }
  
  .item-info-failed {
    background: url("../assets/images/failed.png") no-repeat center;
    background-size: 12px;
    width: 12px;
    height: 12px;
    margin-right: 2px;
  }
  
  .item-info-sending {
    background: url("../assets/images/pending.gif") no-repeat center;
    background-size: 12px;
    width: 12px;
    height: 12px;
    margin-right: 2px;
  }
  
  .router-link-active {
    background: #eeeeee;
    border-radius: 5px;
  }
  
  .conversation-main {
    flex: 1;
    background: #FFFFFF;
    height: 650px;
    overflow:hidden;
  }
  </style>